#!/usr/bin/python -u
# -*- coding: utf-8 -*-
from subprocess import *
from signal import *
import os
import datetime
import sys
import time
import dbus

CHECK_DELAY = datetime.timedelta(minutes=4) # Time to sleep between checks

bus = dbus.Bus(dbus.Bus.TYPE_SESSION)
devobj = bus.get_object('org.freedesktop.PowerManagement', '/org/freedesktop/PowerManagement/Inhibit')
dev = dbus.Interface (devobj, "org.freedesktop.PowerManagement.Inhibit")
inhibitList = {}

class powerDown:
    def __init__(self):
        self.pluginList = {}
        for x in os.listdir("plugins"):
            if os.path.splitext(x)[1] == '.py':
                print "Loading","plugins/" + x
                self.load_plugin("plugins/",x)
        self.selfTest()
        self.run()
            
    def load_plugin(self,path,filename):
        if not os.path.isfile(path+filename):
            return
        f = open(path+filename)
        script = f.read()
        exec(script) in globals()
        try:
            x =  Plugin()
            self.pluginList[x.name()] = x
        except Exception, inst:
            print "Failed loading plugin",filename,inst
            raise "Failed loading plugin",filename,inst
    
    def Inhibit(self,name,reason):
        if inhibitList.has_key(name + "-powerDown"):
            return
        inhibitList[name + "-powerDown"] = dev.Inhibit(name + "-powerDown",reason)
        print "+block \"%s\" reason : %s (count %d)" % (name,reason,len(inhibitList)), inhibitList[name + "-powerDown"]
    
    def Uninhibit(self,name):
        if inhibitList.has_key(name  + "-powerDown"):
            print "-block : \"%s\" (count %d)" % (name, len(inhibitList) - 1),inhibitList[name + "-powerDown"]
            dev.UnInhibit(inhibitList[name + "-powerDown"])
            del inhibitList[name + "-powerDown"]
    
    def selfTest(self):
        print "SelfTest"
        for name in self.pluginList:
            plugin = self.pluginList[name]
            print name, plugin.check()
        print "SelfTest ok"
    
    def scan(self):
        #print "Scan:"
        for name in self.pluginList:
            plugin = self.pluginList[name]
            try:
                msg = plugin.check()
            except Exception, inst:
                print "* Exception raised in plugin",name,inst
            #print "    Checking",name,msg
            if (msg):
                self.Inhibit(name,msg)
            else:
                self.Uninhibit(name)
        #print "Blockers:",
        #for x in inhibitList.keys():
        #    print x,
        #print "\n-------------------------"
    
    def run(self):
        while True:
            self.scan()
            sys.stdout.flush()
            time.sleep(CHECK_DELAY.seconds)
    
def cleanup():
    print "Cleaning up"
    for plugin in inhibitList:
        print "-block",plugin,inhibitList[plugin]
        dev.UnInhibit(inhibitList[plugin])
    
def handler(signum, frame):
    #for pid in killPid:
    #    os.kill(pid,SIGTERM)
    print "Done, exiting"
    cleanup()
    sys.exit(0)
    
    

arguments = sys.argv[1:]
signal(SIGINT, handler)
signal(SIGTERM, handler)

try:
    powerDown()
except Exception, inst:
    print "* Exception raised",inst
    handler(None,None)
cleanup()
